package cn.jisol.ngame.network.entity;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.jisol.ngame.network.JNetwork;
import cn.jisol.ngame.util.ToUtil;
import com.google.protobuf.AbstractMessage;
import com.google.protobuf.Type;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;

import java.io.InputStream;
import java.util.Objects;

/**
 * JNetwork 核心参数
 */
@Getter
@Setter
@Builder
public class JNetParam {

    //请求处理 Id (用来找到处理方法)
    private Integer hId;

    //请求Id (请求标识)
    private Integer id;

    //请求参数
    private byte[] data;

    //格外参数
    private Object[] argsServer;


    /**
     * 解析参数
     * 解析规则: [请求Id*4,处理Id*4,...参数数据*N]
     * 最小包体大小: 9 字节
     */
    public static JNetParam decoder(InputStream stream){

        byte[] bytes = IoUtil.readBytes(stream);

        //必须大于最小包体大小
        if(bytes.length < JNetwork.MINI_DATA) {
            System.out.println("[JNetwork]: 包体大小小于"+JNetwork.MINI_DATA+"byte");
            return null;
        }

        //当前处理的下标
        int index = -1;

        JNetParam.JNetParamBuilder builder = JNetParam.builder();

        //请求Id*4
        builder.id(ToUtil.bytesToInt(new byte[]{bytes[++index],bytes[++index],bytes[++index],bytes[++index]}));
        //处理Id*4
        builder.hId(ToUtil.bytesToInt(new byte[]{bytes[++index],bytes[++index],bytes[++index],bytes[++index]}));

        //消息数据包
        builder.data = ArrayUtil.sub(bytes,++index,bytes.length);

        return builder.build();

    }

    //编码
    public static byte[] encoder(Integer id, Integer hId, AbstractMessage data){
        if(Objects.isNull(data)){
            return ArrayUtil.addAll(ToUtil.intToBytes(id),ToUtil.intToBytes(hId));
        }
        return ArrayUtil.addAll(ToUtil.intToBytes(id),ToUtil.intToBytes(hId),data.toByteArray());
    }

}
